package service

import (
	_ "fmt"
	"go_code/project1/pro/customerManager/model"
)

type UserService struct {
	users []model.User
	num   int // 生成下一个id, 保证id递增 不重复
}

func GetUserService() *UserService {
	this := &UserService{}
	user := model.GetUser(1, 18, "jack", "male", "11111111111", "78@12.com")
	this.users = append(this.users, user)
	this.num = 2
	return this
}

func (this *UserService) List() []model.User {
	if this.users != nil {
		return this.users
	}
	return nil
}

func (this *UserService) Add(user model.User) {
	user.Id = this.num
	this.users = append(this.users, user)
	this.num++
}

func (this *UserService) Update(id int, user model.User) bool {
	if id < 0 || id > this.num {
		return false
	}
	for index, user := range this.users {
		if user.Id == id {
			this.users[index] = user
			return true
		}
	}
	return false
}

func (this *UserService) Delete(id int) bool {
	if id < 0 || id > this.num {
		return false
	}

	flag := -1
	for index, val := range this.users {
		if val.Id == id {
			flag = index
			break
		}
	}

	if flag == -1 {
		return false
	}

	if flag == this.users[0].Id {
		this.users = this.users[1:]
	} else if flag == this.users[len(this.users)-1].Id {
		this.users = this.users[:len(this.users)-1]
	} else {
		this.users = append(this.users[:flag], this.users[flag+1:]...)
	}

	return true
}
